package com.mf.service.authority.impl;

import com.mf.common.sso.LoginContext;
import com.mf.common.utils.PropertyUtils;
import com.mf.constant.MFConstant;
import com.mf.dao.authority.UserPortraitDao;
import com.mf.domain.authority.UserPortrait;
import com.mf.service.authority.UserPortraitService;
import com.mf.service.framework.GenericService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.util.Date;

/**
 * 用户头像信息Service层实现类
 * User: zhaoming
 * DateTime: 2016-07-15
 * To change this template use File | Settings | File Templates.
 **/
@Service
public class UserPortraitServiceImpl extends GenericService<UserPortrait> implements UserPortraitService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private UserPortraitDao userPortraitDao;

    /**
     * 上传图片文件
     * @param multipartFile 上传文件
     * @param userCode 用户编码
     */
    @Transactional
    public UserPortrait uploadImageFile(MultipartFile multipartFile, String userCode){

        String currentUserCode = LoginContext.getLoginUser().getUserCode();
        String filePath = PropertyUtils.getProperty("file.storage.path.root");
        String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        String fileName = userCode + suffix;
        String imagePath = filePath + File.separator + MFConstant.IMAGE_GATEGORY_PROTRAIT + File.separator;

        try {
            InputStream inputStream = multipartFile.getInputStream();
            FileUtils.forceMkdir(new File(imagePath));
            FileUtils.touch(new File(imagePath + File.separator + fileName));
            FileOutputStream out = new FileOutputStream(imagePath + File.separator + fileName);
            byte[] buffer =new byte[1024 * 1024];
            int byteread = 0;
            while ((byteread = inputStream.read(buffer))!=-1)
            {
                out.write(buffer,0,byteread);
                out.flush();
            }
            out.close();
            inputStream.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException("写入图片文件失败" + e.getMessage(), e);
        }

        UserPortrait userPortrait = new UserPortrait();
        userPortrait.setFilePath(filePath);
        userPortrait.setFileName(fileName);
        userPortrait.setFileSuffix(suffix.substring(1));
        userPortrait.setCreateUser(currentUserCode);
        userPortrait.setCreateTime(new Date());
        userPortrait.setUpdateUser(currentUserCode);
        userPortrait.setUpdateTime(new Date());
        userPortraitDao.insert(userPortrait);
        return userPortrait;
    }

    /**
     * 查看图片
     * @param userPortraitId 用户头像ID
     */
    public ResponseEntity<byte[]> show(Long userPortraitId){
        ResponseEntity<byte[]> responseEntity = null;
        UserPortrait userPortrait = userPortraitDao.selectByPrimaryKey(userPortraitId);
        String fileStoryPath = userPortrait.getFilePath() + File.separator + MFConstant.IMAGE_GATEGORY_PROTRAIT + File.separator + userPortrait.getFileName();
        try {
            InputStream inputStream = new BufferedInputStream(new FileInputStream(fileStoryPath));
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);
            headers.setContentDispositionFormData("attachment", new String((userPortrait.getFileName()).getBytes("gbk"),"iso-8859-1"));
            responseEntity = new ResponseEntity(IOUtils.toByteArray(inputStream), headers, HttpStatus.CREATED);
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return responseEntity;
    }


}
